<template>
  <div class="tem">
    <div class="cascade mb20">
      <HadayFoldFiltrate :data="foldData" :props="props" styleType="autoWidth" @item-change="itemChange">     
        <template #labelPanel="slotProps">
          {{ slotProps.child[props.label] }}
        </template>
        <template #lineMorePanel>
          更多<i class="el-icon-arrow-down"></i>
        </template>
      </HadayFoldFiltrate>
    </div>
    <!-- <div class="project-info">
      <span>排序：</span>
      <ul class="left-side">
        <li>
          <span :class="levelOrder == 'Asc' ? 'fontred' : 'fontgreen'" @click="handleSort('levelOrder')"
            >已完成个数<i class="iconfont icon-sort_icon"></i>
          </span>
        </li>
        <li>
          <span :class="startTimeOrder == 'Asc' ? 'fontgreen' : 'fontred'" @click="handleSort('startTimeOrder')"
            >未完成个数<i class="iconfont icon-sort_icon"></i>
          </span>
        </li>
      </ul>
    </div> -->
    <template v-if="taskFlag === 'personal'">
      <div style="display:flex;    justify-content: space-between;">
        <h5>任务单汇总：
           <span>总任务:<em>{{sortPersonal.taskCountAll}}</em></span>
           <span>已完成:<em>{{sortPersonal.completedCountAll}}</em></span>
           <span>未完成:<em>{{sortPersonal.inCompletedCountAll}}</em></span>
           <span>延迟的:<em>{{sortPersonal.delayCountAll}}</em></span>
           <span>提前完成的:<em>{{sortPersonal.advanceCompletedTotalAll}}</em></span>
           <span>及时率:<em>{{sortPersonal.timelinessRate || 0}}%</em></span>
           <span>完成率:<em>{{sortPersonal.completionRate || 0}}%</em></span>
           <span v-if="updateTime != ''">最近一次更新时间：{{updateTime}}</span>
        </h5>
        <div>
            <a-button v-if="dataPermissionFlag" type="primary" @click="searchClick"  style="margin-top: -5px;margin-right:5px;"><a-icon type="search" />{{searchText}}</a-button>
            <a-button v-if="dataPermissionFlag" @click="exportWebXls"  style="margin-top: -5px;"><a-icon type="download" />导出列表</a-button>
        </div>
      </div>

      <div class="score-card score-card-chrome" v-if="userAgentStr === 'Chrome'">
        <div>
          我的总任务个数
          <div class="num-box-item" v-for="(item, index) in computeNumber0" :key="index">
            <span ref="numberItem0">0123456789</span>
          </div>
        </div>
        <div>
          我的已完成任务个数
          <div class="num-box-item" v-for="(item, index) in computeNumber1" :key="index">
            <span ref="numberItem1">0123456789</span>
          </div>
        </div>
        <div>
          我的排名
          <div class="num-box-item" v-for="(item, index) in computeNumber2" :key="index">
            <span ref="numberItem2">0123456789</span>
          </div>
        </div>
        <!-- <div>
          我已击败人数
          <div class="num-box-item" v-for="(item, index) in computeNumber3" :key="index">
            <span ref="numberItem3">0123456789</span>
          </div>
        </div> -->
      </div>
      <div class="score-card" v-else>
        <div>
          总任务个数<em>{{ sortPersonal.taskCount || 0 }}</em>
        </div>
        <div>
          已完成任务个数<em>{{ sortPersonal.completedCount || 0 }}</em>
        </div>
        <div>
          目前排名<em>{{ sortPersonal.rankCount || 0 }}</em>
        </div>
        <div>
          已击败人数<em>{{ sortPersonal.beatCount || 0 }}</em>
        </div>
      </div>
    </template>
     <template v-if="taskFlag != 'personal' && dataPermissionFlag">
      <div style="display:flex;    justify-content: space-between;">
        <h5>
          <span v-if="updateTime != ''">最近一次更新时间：{{updateTime}}</span>
        </h5>
        <div>
            <a-button v-if="dataPermissionFlag" @click="exportWebXls"><a-icon type="download" />导出列表</a-button>
        </div>
      </div>
    </template>
    <div class="content-list" :class="{ mt20: taskFlag !== 'personal' }" :style="{ marginTop: (taskFlag != 'personal' && dataPermissionFlag) ? '10px':'20px'}">
      <a-table
        class="reservation-content"
        :columns="reservationColumns"
        :data-source="reservationData"
        :pagination="pagination"
        :loading="tabLoading"
        bordered
        size="middle"
        @change="pageChange"
      >
        <span slot="rank" slot-scope="text, record, index">
          <i v-if="index === 0 && currPageIndex === 1" class="iconfont-m icon-no1"></i>
          <i v-else-if="index === 1 && currPageIndex === 1" class="iconfont-m icon-no2"></i>
          <i v-else-if="index === 2 && currPageIndex === 1" class="iconfont-m icon-no3"></i>
        </span>
        <span slot="timeliness" class="progess-slot" slot-scope="text">
          <i class="pro-color">{{ text }}%</i><a-progress :percent="text" :show-info="false" />
        </span>
        <span slot="completion" class="progess-slot" slot-scope="text">
          <i class="pro-color">{{ text }}%</i><a-progress :percent="text" :show-info="false" />
        </span>
        <template slot="operation" slot-scope="text, record" class="det-slot">
          <a @click="handledispose(record)">明细</a>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import { getAction, downloadFileLink } from '@/api/manage'
import { codeInfoList } from '@/api/codeInfo'
import moment from 'moment'
import Vue from 'vue'
import {Checkbox, CheckboxGroup} from 'element-ui'; 
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
export default {
  name: 'TaskPersonal',
  props: {
    searchVal: {
      type: String,
      default: '',
    },
    taskFlag: {
      type: String,
      default: 'personal',
      required: true,
    },
  },
  data() {
    return {
      foldData:[],
      props:{
         label: 'name',
         key: 'code', 
         children: 'children', 
         activedKey: 'activedKey'
      },
      searchText:'查看全部',
      deptOrAllFlag: true,
      dataPermissionFlag: false,
      levelOrder: '', // 排序
      startTimeOrder: '',
      pagination: {
        total: 0,
        current: 1,
      },
      currPageIndex: 1,
      currPageSize: 10,
      valueSearch: '',
      reserTeamColumns: [
        {
          title: '',
          key: 'rank',
          align: 'center',
          dataIndex: 'rank',
          width: '2%',
          scopedSlots: { customRender: 'rank' },
        },
        {
          title: '团队名称',
          dataIndex: 'teamName',
          width: '18%',
          align: 'center',
        },
        {
          title: '整体任务情况',
          children: [
            {
              title: '总数量',
              dataIndex: 'taskTotal',
              width: '6%',
              align: 'center',
            },
            {
              title: '已完成数量',
              dataIndex: 'completedTotal',
              width: '6%',
              align: 'center',
            },
            {
              title: '未完成数量',
              dataIndex: 'incompletedTotal',
              width: '6%',
              align: 'center',
            }
          ]
        },
        {
          title: '已完成任务情况',
          children: [
            {
              title: '提前完成数量',
              dataIndex: 'advanceCompletedTotal',
              width: '6%',
              align: 'center',
            },
            {
              title: '按时完成数量',
              dataIndex: 'onTimeCompletedTotal',
              width: '6%',
              align: 'center',
            },
            {
              title: '延误完成数量',
              dataIndex: 'completedTotalButDelay',
              width: '6%',
              align: 'center',
            }
          ]
        },
        {
          title: '未完成任务情况',
          children: [
            {
              title: '到期未完成数量',
              dataIndex: 'delayTotal',
              width: '6%',
              align: 'center',
            },
            {
              title: '未到期数量',
              dataIndex: 'incompletedTotalButOnTime',
              width: '6%',
              align: 'center',
            }
          ]
        },
        {
          title: '及时率',
          dataIndex: 'timeliness',
          width: '13%',
          align: 'center',
          scopedSlots: { customRender: 'timeliness' },
        },
        {
          title: '完成率',
          dataIndex: 'completion',
          width: '13%',
          align: 'center',
          scopedSlots: { customRender: 'completion' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '6%',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      reservationData: [],
      projectTypes: [],
      taskType: '',
      projectSubType: [
        { name: '全部', code: '5' },
        { name: '已完成', code: '2' },
        { name: '未完成', code: '3' },
        { name: '延误', code: '4' },
      ],
      status: '5',
      tabLoading: false,
      userAgentStr: '',
      sortPersonal: {},
      sortPerNumInfo: {},
      computeNumber0: ['0'],
      computeNumber1: ['0'],
      computeNumber2: ['0'],
      computeNumber3: ['0'],
      yearList: [],
      searchYear:'',
      updateTime: ''
    }
  },
  computed: {
    reservationColumns() {
       let reserPerColumns = Object.assign([], this.reserTeamColumns)
      if (this.taskFlag === 'personal') {
        reserPerColumns.splice(2, 0, {
          title: '部门',
          dataIndex: 'teamName',
          width: '9%',
          align: 'center',
        })
        reserPerColumns.splice(1, 1, {
          title: '姓名',
          dataIndex: 'realName',
          width: '9%',
          align: 'center',
        })
      }
      return this.taskFlag === 'personal' ? [...reserPerColumns] : [...this.reserTeamColumns]
      //return this.taskFlag === 'personal' ? [...this.reserTeamColumnsPerson] : [...this.reserTeamColumns] 
    },
  },
  created() {
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Chrome') > -1) {
      this.userAgentStr = 'Chrome'
    }
  },
  mounted() {
    this.initData() // 查询类型
    this.getTodoListData() // 查询数据
    this.checkPermission()
    if (this.taskFlag === 'personal') this.sortPersonalsonalNum() // 只有个人有排名结果查看
  },
  methods: {
    exportWebXls:function(){
      let that = this;

      let queryParam = {}
      queryParam.pageNo = 1;
      queryParam.pageSize = -1;
      queryParam.taskBuildType = this.taskFlag === 'personal' ? '1' : '2', // 1-个人，2-团队
      queryParam.keyword = this.searchVal;
      queryParam.status = this.status;
      queryParam.taskType = this.taskType;
      queryParam.deptOrAllFlag = this.deptOrAllFlag;
      queryParam.searchYear = this.searchYear;
      const title =  this.taskFlag === 'personal' ? '个人任务单排名导出' : '团队任务单排名导出'
      downloadFileLink('/projectWorkTask/exportWebXlsTwo',title,queryParam,{type: 'application/vnd.ms-excel'});
     
    },
    searchClick() {
      // 查看全部 deptOrAllFlag = false
      // 查看部门 deptOrAllFlag = true
      this.searchText = this.searchText === '查看全部' ? '查看部门' : '查看全部'
      this.deptOrAllFlag = this.searchText === '查看全部' ? true : false
      this.currPageIndex = 1
      this.getTodoListData()
      this.sortPersonalsonalNum()
    },
    initData() {
      let year = parseInt(moment().format('YYYY'))
      this.searchYear = year
      this.yearList.push({ code: '', name: '全部' })
      for (var i = 0; i < 5; i++) {
        if (year - i < 2020) {
          break; 
        }
        this.yearList.push({ code: year - i + '', name: year - i })
      }

      if (this.$ls.get('TaskProjectTypes')) {
        const list = this.$ls.get('TaskProjectTypes')
        if (list.length > 0) {
          this.projectTypes = list
          this.setFoldDataList('taskType', this.projectTypes, '项目类型：')
          // this.setFoldDataList('status', this.projectSubType, '状态：')
          this.setFoldDataList('searchYear', this.yearList, '年份：')
          return
        }
      }

      getAction('/projectWorkTask/querytaskUsedProjectClassList')
        .then((res) => {
          if (res.code == 200 && res.result) {
            this.projectTypes = res.result || []
            this.projectTypes.splice(0, 0, { code: '', name: '全部', type: '我的任务分类', isdel: '0', parentid: '' })
            this.$ls.set('TaskProjectTypes', this.projectTypes)
            this.setFoldDataList('taskType', this.projectTypes, '项目类型：')            
            // this.setFoldDataList('status', this.projectSubType, '状态：')
            this.setFoldDataList('searchYear', this.yearList, '年份：')
          } else {
            this.$message.warning('我的任务分类加载失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('我的任务分类加载失败:' + res.message)
        })
    },
    setFoldDataList(type, list, name){
      const pro = {
        children: list,
        activedKey: this[type] || list[0].code,
        model: type,
        name,
        type: 'text'
      }
      this.foldData.push(pro)
    },
    getTodoListData() {
      this.tabLoading = true
      getAction('/projectWorkTask/list', {
        pageSize: this.currPageSize,
        pageNo: this.currPageIndex,
        status: this.status,
        taskBuildType: this.taskFlag === 'personal' ? '1' : '2', // 1-个人，2-团队
        keyword: this.searchVal,
        taskType: this.taskType,
        deptOrAllFlag: this.deptOrAllFlag,
        searchYear: this.searchYear
        // order: 'desc',
      }).then((res) => {
        if (res.code == 200 && res.result) {
          this.pagination.total = res.result.total
          res.result.records.forEach((item, index) => {
            item.key = this.taskFlag + index
            item.completion = item.taskTotal === 0 ? 0 :Math.round((item.completedTotal / item.taskTotal) * 10000) / 100 // 完成率（已完成/总任务）
            // 及时率＝（提前完成+按时完成onTimeCompletedTotal）/到期数expireTotal
            item.timeliness = item.expireTotal === 0 ? 0 :Math.round( ((item.advanceCompletedTotal + item.onTimeCompletedTotal) / item.expireTotal) * 10000) / 100     
            this.updateTime = item.updateTime || ''        
          })
          this.reservationData = res.result.records
          this.tabLoading = false
        } else {
          this.$message.warning('数据加载失败:' + res.message)
          this.tabLoading = false
        }
      }).catch((res) => {
          this.$message.warning('数据加载失败,请切换搜索栏进行搜索')
          this.tabLoading = false
        })
    },
    pageChange(page) {
      this.currPageIndex = page.current
      this.currPageSize = page.pageSize
      this.pagination.current = page.current
      this.getTodoListData()
    },
    handleSearch() {
      this.currPageIndex = 1
      this.getTodoListData()
      this.sortPersonalsonalNum()
    },
    handledispose(record) {    
      getAction('/projectWorkTask/checkPermission', {}).then((res) => {
        if (res.code == 200) {
          if(res.result){
            // 如果是管理员点击，则跳转到对应的人或对应的科室架构的任务明细
            this.$emit('backDetHome', 0, this.taskFlag === 'personal' ? record.realName : record.teamName,this.taskFlag,this.searchYear,'permissionFlag')
          }else{
            this.$emit('backDetHome', 0, this.taskFlag === 'personal' ? record.realName : record.teamName,this.taskFlag,this.searchYear)
          }        
        } else {
          this.$message.warning('查询权限失败:' + res.message)
        }
      })       
    },

    /**
     * 切换类别
     */
    handleToggle(code, codeRef) {
      this[codeRef] = code
      this.currPageIndex = 1
      this.getTodoListData()
      this.sortPersonalsonalNum()
    },
    itemChange(item, child, val){
      this[item.model] = child.code
      this.currPageIndex = 1
      this.getTodoListData()
      this.sortPersonalsonalNum()
    },
    /**
     * 排序
     */
    handleSort(type) {
      this[type] = this[type] === 'Asc' ? 'desc' : 'Asc'
      this.currPageIndex = 1
      this.getTodoListData()
    },

    /**
     * 排名数字动画
     */
    sortPersonalsonalNum() {
      const _this = this
      getAction('/projectWorkTask/queryRank', {
        pageSize: this.currPageSize,
        pageNo: this.currPageIndex,
        status: this.status,
        taskBuildType: this.taskFlag === 'personal' ? '1' : '2', // 1-个人，2-团队
        keyword: this.searchVal,
        taskType: this.taskType,
        deptOrAllFlag: this.deptOrAllFlag,
        searchYear: this.searchYear
        // order: 'desc',
      }).then((res) => {
        if (res.code == 200 && res.result) {
          Object.assign(this.sortPersonal, res.result)
          if (this.userAgentStr === 'Chrome') {
            this.computeNumber0 = res.result.taskCount ? String(res.result.taskCount).split('') : ['0']
            this.computeNumber1 = res.result.completedCount ? String(res.result.completedCount).split('') : ['0']
            this.computeNumber2 = res.result.rankCount ? String(res.result.rankCount).split('') : ['0']
            this.computeNumber3 = res.result.beatCount ? String(res.result.beatCount).split('') : ['0']

            setTimeout(()=>{
              _this.setNumberTransform()
            }, 100)
          }
          //this.dataPermissionFlag = res.result.dataPermissionFlag
        } else {
          this.$message.warning('数据加载失败:' + res.message)
        }
      })
    },
    checkPermission() {
       getAction('/projectWorkTask/checkPermission', {}).then((res) => {
        if (res.code == 200) {
          if(res.result){
            this.dataPermissionFlag = true
          }else{
             this.dataPermissionFlag = false
          }        
        } else {
          this.$message.warning('查询权限失败:' + res.message)
        }
      }) 
    },
    setNumberTransform() {
      // 设置每一位数字的偏移
      const _this = this
      for (let index = 0; index < 3; index++) {
        const numberItems = _this.$refs['numberItem' + index]
        if (numberItems) {
          const comNum = _this['computeNumber' + index]
          for (let index = 0; index < numberItems.length; index++) {
            const elem = numberItems[index]
            elem.style.transform = `translate(-50%, -${comNum[index] * 10}%)`
            if (index > 0) {
              elem.style.transition = `transform 0.${index * 2}s ease-in-out`
            }
          }
        }
        
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import 'task.less';
.content-list {
  background-color: #fff;
  &.mt20 {
    margin-top: 20px;
  }
}
.task-main .container .cascade.mb20 {
  margin-bottom: 10px;
}
.progess-slot {
  display: flex;
  .pro-color {
    color: @font-color-active;
    padding-right: 5px;
    font-style: inherit;
    width: 105px;
    text-align: right;
  }
}
.det.slot {
  color: @bg-color-btn;
}
h5 {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  margin-left: 15px;
  flex:1;
  span{
    margin-right: 18px;
    em{font-style: normal;color: #249af4;margin-left: 5px;}
  }  
}
.score-card {
  height: 80px;
  line-height: 80px;
  background-color: #404b5c;
  box-shadow: 0px 2px 7px 0px #b5bbc4, inset 0px 2px 4px 0px #7a889f;
  border-radius: 8px;
  margin-bottom: 13px;
  display: flex;
  user-select: none;
  &.score-card-chrome{
    line-height: 85px;
  }
  > div {
    color: #bdc7d8;
    position: relative;
    display: inline-block;
    flex: 1;
    text-align: center;
    &:after {
      &:extend(.afterbg);
      width: 2px;
      height: 43px;
      top: 50%;
      margin-top: -21px;
      background-color: #27354a;
    }
    em {
      font-size: 30px;
      font-weight: bold;
      margin-left: 6px;
    }
    &:nth-child(1) {
      .num-box-item,
      em {
        color: #5adeff;
      }
    }
    &:nth-child(2) {
      .num-box-item,
      em {
        color: #ec83ff;
      }
    }
    &:nth-child(3) {
      .num-box-item,
      em {
        color: #ff9e56;
      }
    }
    &:nth-child(4) {
      .num-box-item,
      em {
        color: #27d893;
      }
    }
    &:last-of-type{
      &:after{display: none;}
    }
  }  
}

.num-box-item {
  display: inline-block;
  width: 30px;
  position: relative;
  -ms-writing-mode: tb-lr;
  writing-mode: vertical-lr;
  writing-mode: tb-rl;
  text-orientation: upright;
  overflow: hidden;
  font-size: 33px;
  font-weight: bold;
  height: 40px;
  line-height: 40px;
  top: 2px;
  /* font-style: oblique; */
  width: 20px;
  span {
    position: absolute;
    top: 10px;
    left: 50%;
    transform: translate(-50%, -0%);
    transition: transform 0.8s ease-in-out;
    letter-spacing: 10px;
  }
}

.reservation-content {
  /deep/ .ant-table-body {
    background-color: #fff;
  }
  /deep/ .ant-table-thead > tr > th{
    border: 1px solid #bfbfbf;
  }
  /deep/ .ant-table-thead,
  /deep/ .ant-table-thead > tr > th {
    background-color: #d9dee8;
  }
  /deep/ .ant-table-small > .ant-table-content > .ant-table-body {
    margin: 0;
    border: 0;
  }
  /deep/ .ant-table-thead > tr:first-child > th:last-child {
    border-top-right-radius: 0;
  }
  /deep/ .ant-table-small > .ant-table-content .ant-table-row:last-child td {
    border-bottom: 1px solid #e8e8e8;
  }
}
</style>